package com.example.tencent_cos_flutter;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener; 
import com.example.tencent_cos_flutter.MySessionCredentialProvider;
import android.content.Context;
import android.app.Activity;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import java.lang.Thread;
import java.lang.Runnable;

/** TencentCosFlutterPlugin */
public class TencentCosFlutterPlugin implements FlutterPlugin,ActivityAware, MethodCallHandler {

  private MethodChannel channel;
  private Activity activity;

  	@Override
	  public void onAttachedToActivity(ActivityPluginBinding binding) {
	    activity = binding.getActivity();
	  }
	
	  @Override
	  public void onDetachedFromActivityForConfigChanges() {
	    this.onDetachedFromActivity();
	  }
	
	  @Override
	  public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
	    this.onAttachedToActivity(binding);
	  }
	
	  @Override
	  public void onDetachedFromActivity() {
	    activity = null;
	  }


  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "tencent_cos_flutter");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
   if (call.method.equals("upload")) {
    initOSSWithPath(
      (String)(call.argument("path")),
      (String)(call.argument("cosUrl")),
      (String)(call.argument("bucket")),
      (String)(call.argument("tmpSecretId")),
      (String)(call.argument("tmpSecretKey")),
      (String)(call.argument("sessionToken")),
      (String)(call.argument("region")),
      Long.parseLong((String)(call.argument("startTime"))),
      Long.parseLong((String)(call.argument("expiredTime"))),
      result);


    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }


private void initOSSWithPath(
  String path,
  String cosUrl,
  String bucket,
  String tmpSecretId,
  String tmpSecretKey,
  String sessionToken,
  String region,
  long startTime,
  long expiredTime,
  @NonNull Result callback) {
// 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
                .builder();
// 初始化 COS Service，获取实例
        CosXmlService cosXmlService = new CosXmlService(activity.getApplicationContext(),
                serviceConfig, new MySessionCredentialProvider(tmpSecretId, tmpSecretKey,
                sessionToken, startTime, expiredTime));
        upLoadWithPath(cosXmlService, path,cosUrl,bucket,callback);
    }


    private void upLoadWithPath(CosXmlService cosXmlService, String path, String cosUrl,String bucket, @NonNull Result callback) {
      final Result callbacks = callback;
        TransferConfig transferConfig = new TransferConfig.Builder().build();
// 初始化 TransferManager
        TransferManager transferManager = new TransferManager(cosXmlService,
                transferConfig);
 
// 上传文件
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosUrl, path,null);
//设置上传进度回调
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long complete, long target) {


            }
        });
//设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                // Log.e("地址", result.accessUrl);
                final String urlStr = result.accessUrl;
                 activity.runOnUiThread(new Thread(new Runnable() {
                    @Override
                    public void run() {
                         callbacks.success(urlStr);
                    }
                }));
               

            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                 activity.runOnUiThread(new Thread(new Runnable() {
                    @Override
                    public void run() {
                         callbacks.success("");
                    }
                }));
            

            }
        });
    //设置任务状态回调, 可以查看任务过程
        cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(TransferState state) {
            }
        });
    }
}

